﻿#include <iostream>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <winsock2.h>
#define BUF_SIZE 1024
void ErrorHandle(const char *message);
int main(int argc, char *argv[])
{
  WSADATA wsadata; // 初始化操作的信息（output）
  SOCKET sock_serv, sock_clnt;
  WSAStartup(MAKEWORD(2, 2), &wsadata); // 初始化Winsock库；
  // step01:创建套接字
  sock_serv = socket(PF_INET, SOCK_STREAM, 0);
  SOCKADDR_IN addr_serv;
  memset(&addr_serv, 0, sizeof(addr_serv));
  // step02：给套接字设置IP和端口号
  addr_serv.sin_family = AF_INET;
  addr_serv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
  addr_serv.sin_port = htons(atoi(argv[1]));
  auto bind_result = bind(sock_serv, (SOCKADDR *)&addr_serv, sizeof(addr_serv));
  if (bind_result == SOCKET_ERROR)
    ErrorHandle("bind() error!");
  std::cout << "bind() ok..." << std::endl;
  // step03：转入等待连接请求状态
  auto listen_result = listen(sock_serv, 5);
  if (listen_result == SOCKET_ERROR)
    ErrorHandle("listen() error!");
  std::cout << "listen() ok..." << std::endl;

  SOCKADDR_IN addr_clnt;
  int size_addr_clnt = sizeof(addr_clnt);
  int i = 0;
  while (i < 5)
  {
    // step04：接收请求连接
    sock_clnt = accept(sock_serv, (SOCKADDR *)&addr_clnt, &size_addr_clnt);
    if (sock_clnt == SOCKET_ERROR)
      ErrorHandle("accept() error!");
    std::cout << "connected client " << i << std::endl;
    char message[BUF_SIZE];
    auto strlen = recv(sock_clnt, message, BUF_SIZE, 0);
    std::cout << "Receive message from client(" << strlen << "):" << message << std::endl;
    if (strlen != 0)
    {
      std::string mess_clnt = std::string(message);
      mess_clnt.erase(mess_clnt.length() - 1);
      std::string mes_return = mess_clnt + "(message from server)";
      strlen = mes_return.length();
      const char *mes_response = mes_return.c_str();
      send(sock_clnt, mes_response, strlen, 0);
      closesocket(sock_clnt);
    }
    ++i;
  }
  closesocket(sock_serv);
  WSACleanup();
  return 0;
}
void ErrorHandle(const char *message)
{
  std::cout << message << std::endl;
  exit(-1);
}